import numpy as np
from math import sqrt
# 执行in_chebyshevs_interval()函数时会完成概率记录，存放在proba_rate
# 改变量是为了绘制ROC曲线做准备的

proba_rate=[]

def get_len_set(data_set):
    """
    由字符串训练集生成长度训练集
    """
    len_set = []
    for x in data_set:
        len_set.append(len(x))
    return len_set


def get_mean(l):
    "get the mean of a list efficiently with NumPy"
    N = len(l)
    narray = np.array(l)
    sum = narray.sum()
    mean = sum / N
    return mean


def get_var(l):
    "get the variance of a list efficiently with NumPy"
    N = len(l)
    mean = get_mean(l)
    narray = np.array(l)
    narray2 = narray * narray
    sum2 = narray2.sum()
    var = sum2 / N - mean**2
    return var


def get_stdev(l):
    "get the standard deviation of a list with get_var() and math.sqrt()"
    var = get_var(l)
    stdev = sqrt(var)
    return stdev


def in_chebyshevs_interval(x, mean, stdev, pct):
    "judge the input value 1"
    "x: sample; mean: average value; stdev: standard deviation; pct: percentage"
    "根据参数长度数值集的计算的阈值结果做判断"
    m = int(sqrt(1 / (1 - pct * 0.01)))
    is_in_chebyshevs_interval = 0
    if mean - m * stdev <= x and x <= mean + m * stdev:
        is_in_chebyshevs_interval = 1
    return is_in_chebyshevs_interval

def makeDecesionByScore(x,bottom,top):
    """
    由指定阈值做决策
    params:
    x:样本
    top:指定的阈值上限
    bottom:指定的阈值下限
    """
    if bottom <= x and x <= top:
        return 1
    else:
        return 0

# proba_rate有关变量或者函数请暂时忽略
def recordProba_rate(mean, stdev, pct):

    global proba_rate
    m = int(sqrt(1 / (1 - pct * 0.01)))
    top=mean + m * stdev
    bottom=mean - m * stdev
    temp=(bottom,top)
    proba_rate.append(temp)
def setProba_rate(probas):
    global proba_rate
    proba_rate=probas

def getProba_rate():
    global proba_rate
    return sorted(proba_rate,reverse=True,key=lambda tmp:tmp[1]-tmp[0])



def toDocRecord(var,mean,stdev,route,fld):
    """
    生成训练结果的文本文件存档，对应参数名生成txt文件...
    好像没什么用了...
    到时候再说吧...
    params:
    var,mean,stdev:你懂得
    route:存储的目录
    fld：存储的文件名，txt格式
    """
    f=open(route+"//"+fld+".txt","w",encoding="utf-8")
    f.write("var="+str(var)+"\nmean="+str(mean)+"\nstdev="+str(stdev))

def returnRst(l):
    return get_mean(l),get_var(l),get_stdev(l)

def predict(samples,mean,stdev,pct):
    # 对样本集做出预测
    "samples:list of parameters' value"
    result=list()
    for x in samples:
        result.append(in_chebyshevs_interval(x,mean, stdev, pct))
    return result



if __name__ == '__main__':
    def test(l=[1, 2, 3, 4, 5]):
        print(get_mean(l))
        print(get_var(l))
        print(get_stdev(l))
        print(in_chebyshevs_interval(9, 3, 1.414, 90))


    test()
